package com.loong.user.handler;

import com.loong.common.domain.BaseQuery;
import com.loong.common.domain.Pager;
import com.loong.common.utils.TransformUtils;
import com.loong.user.business.ManageRoleBusiness;
import com.loong.user.common.backend.param.ManageApiQueryParam;
import com.loong.user.common.backend.param.ManageRoleParam;
import com.loong.user.common.backend.param.ManageRoleQueryParam;
import com.loong.user.common.backend.result.ManageApiResult;
import com.loong.user.common.backend.result.ManageRoleResult;
import com.loong.user.model.ManageApi;
import com.loong.user.model.ManageResource;
import com.loong.user.model.ManageRole;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 系统角色服务
 * @Author: hzp
 * @Date: 2020-10-16 17:16
 */
@Component
public class ManageRoleHandler {
    @Resource
    private ManageRoleBusiness manageRoleBusiness;

    /**
     * 保存后台系统角色
     * @param param
     */
    public void save(ManageRoleParam param){
        manageRoleBusiness.save(TransformUtils.transform(param, ManageRole.class));
    }

    /**
     * 更新后台系统角色
     * @param param
     */
    public void update(ManageRoleParam param){
        manageRoleBusiness.updateByPrimaryKeySelective(TransformUtils.transform(param, ManageRole.class));
    }

    public void deleteById(List<Long> ids){
        if(ObjectUtils.isEmpty(ids)){return;}
        manageRoleBusiness.deleteByIds(StringUtils.join(ids,","));
    }
    /**
     *根据ids删除系统角色 递归删
     * @param ids 角色ids
     */
    public void deleteByIds(List<Long> ids){
        if(ObjectUtils.isEmpty(ids)){return;}
        List<ManageRole> allResourceList=manageRoleBusiness.findAll();
        List<ManageRoleResult> resourceResultList = TransformUtils.transformList(allResourceList, ManageRoleResult.class);
        Set<Long> allIds = new HashSet<>();
        ids.forEach(id->{
            ManageRoleResult root = ManageRoleResult.builder().id(id).build();
            getChildrenIds(root,resourceResultList,allIds);
        });
        allIds.addAll(ids);
        String deleteIds = StringUtils.join(allIds, ",");
        manageRoleBusiness.deleteByIds(deleteIds);
    }
    public Set<Long> getChildrenIds(ManageRoleResult root, List<ManageRoleResult> roleList, Set<Long> childrenIds) {
        if(CollectionUtils.isEmpty(roleList))return childrenIds;
        roleList
                .stream()
                .filter(role -> role.getParentId().equals(root.getId()))
                .map(role->{
                    childrenIds.add(role.getId());
                    getChildrenIds(role, roleList,childrenIds);
                    return role;
                })
                .collect(Collectors.toList());
        return childrenIds;
    }




    public List<ManageRoleResult> queryAllRoleTree(){

        List<ManageRole> allResourceList=manageRoleBusiness.findAll();
        List<ManageRoleResult> manageRoleTreeResults = TransformUtils.transformList(allResourceList, ManageRoleResult.class);
        // toTree
        return toTree(manageRoleTreeResults);
    }

    public List<ManageRoleResult> toTree(List<ManageRoleResult> manageRoleResultList) {
        if(CollectionUtils.isEmpty(manageRoleResultList))return manageRoleResultList;
        return manageRoleResultList
                .stream()
                .filter(roleTreeResult -> roleTreeResult.getParentId() == 0)
                .map(roleTreeResult -> {
                    roleTreeResult.setChildren(getChildren(roleTreeResult, manageRoleResultList));
                    return roleTreeResult;
                })
                //.sorted(Comparator.comparing(ManageResourceResult::getSort))
                .collect(Collectors.toList());
    }

    public List<ManageRoleResult> getChildren(ManageRoleResult root, List<ManageRoleResult> roleResultList) {
        if(CollectionUtils.isEmpty(roleResultList))return roleResultList;
        List<ManageRoleResult> collect = roleResultList
                .stream()
                .filter(category -> category.getParentId().equals(root.getId()))
                .map(category->{
                    List<ManageRoleResult> children = getChildren(category, roleResultList);
                    category.setChildren(children);
                    return category;
                })
                //.sorted(Comparator.comparing(ManageResourceResult::getSort))
                .collect(Collectors.toList());
        // 表示没子节点了
        if(CollectionUtils.isEmpty(collect)){
            root.setName(root.getName()+"["+root.getId()+"]");
            // 结束递归
            return new ArrayList<>();
        }
        return collect;
    }

    /**
     * 根据部门id查询角色
     * @param deptId
     * @return
     */
    public List<ManageRoleResult> queryRoleByDeptId(Long deptId) {
        List<ManageRole> roleResult = manageRoleBusiness.findAllBy("departmentId", deptId);
        return TransformUtils.transformList(roleResult, ManageRoleResult.class);
    }


    /**
     * 分页查询
     * @param baseQuery
     * @param param
     * @return
     */
    public Pager<ManageRoleResult> pageQuery(BaseQuery baseQuery, ManageRoleQueryParam param){
        Pager<ManageRole> manageRolesPager = manageRoleBusiness.pageQuery(baseQuery, () -> manageRoleBusiness.query(param));
        return TransformUtils.transformPage(manageRolesPager, ManageRoleResult.class);
    }
}
